//
//  UIImage+Extension.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/9/6.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import Foundation
extension UIImage{
    //截屏功能
    class func getScreenSnap() -> UIImage?{
        let window = UIApplication.shared.keyWindow!
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, 0)
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()
        return image
    }
    /// 缩放到指定的宽度
    ///
    /// - parameter width: <#width description#>
    func scaleTo(width: CGFloat) -> UIImage {
        
        if self.size.width < width {
            return self
        }
        // 根据宽度求出等比例缩放之后的高度
        let height = self.size.height * (width / self.size.width)
        // 定义一个范围
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        // 开启上下文
        UIGraphicsBeginImageContext(rect.size)
        // 会将当前图片的所有内容完整的画到上下文中
        self.draw(in: rect)
        // 取值
        let result = UIGraphicsGetImageFromCurrentImageContext()!
        // 关闭上下文
        UIGraphicsEndImageContext()
        return result
    }

}
